﻿using DJLang;
using System;
using System.Collections.Generic;
using UnityEngine;
using ZerAx.ObjectNotation;

namespace BlockOS.Client.Res
{
    public class Block
    {
        public DJEnv root;
        public IDJValue getBinds;
        public IDJValue getBlockModelDef;

        public Block(IDJValue getBinds, IDJValue getBlockModelDef)
        {
            this.getBinds = getBinds;
            this.getBlockModelDef = getBlockModelDef;
        }

        public BlockModel GetBlockModel(
            Dictionary<string, Zon> states, 
            Dictionary<string, Func<Vector2, Vector2>> converters)
        {
            DJEnv callEnv = new();
            callEnv.parent = root;

            foreach (var (name, state) in states)
            {
                callEnv.Put(name, ParseDJValue(state));
            }
            // 读取纹理列表
            DJList binds = callEnv.ForceEval(getBinds.Clone()) as DJList;
            // 生成模型
            var def = callEnv
                .ForceEval(getBlockModelDef.Clone())
                .GetManaged<BlockModelDef>();
            def.BindTextures(callEnv, binds);
            return def.GetBlockModel(root, converters);
        }

        private IDJValue ParseDJValue(Zon zonVal)
        {
            return zonVal.Type switch
            {
                ZonType.Bool => new DJBasic<bool>(zonVal.As<ZonBool>().data),
                ZonType.I32 => new DJInt(zonVal.As<ZonI32>().data),
                ZonType.F32 => new DJFloat(zonVal.As<ZonF32>().data),
                ZonType.String => new DJString(zonVal.As<ZonString>().data),
                _ => new DJString("null")
            };
        }
    }
}